/*
 *  Copyright 2020-2021 Li Fei
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.pengshun.modules.api.coal.service.impl;

import com.pengshun.modules.api.coal.para.MerchantCoalPara;
import com.pengshun.modules.api.coal.repository.MerchantCoalInfoRepository;
import com.pengshun.modules.api.coal.service.dto.MerchantCoalInfoDto;
import com.pengshun.modules.api.coal.service.mapstruct.MerchantCoalInfoTodo;
import com.pengshun.modules.api.mapper.MerchantCoalMapper;
import com.pengshun.modules.api.mapper.PsCoalMapper;
import com.pengshun.modules.api.coal.para.CoalBinessPara;
import com.pengshun.modules.api.coal.repository.MerchantRepository;
import com.pengshun.modules.api.coal.repository.UserRepository;
import com.pengshun.modules.api.coal.result.MerchantCoalResult;
import com.pengshun.modules.common.*;
import com.pengshun.modules.domain.Merchant;
import com.pengshun.modules.domain.MerchantCoal;
import com.pengshun.modules.domain.MerchantCoalInfo;
import com.pengshun.modules.domain.User;
import lombok.RequiredArgsConstructor;
import com.pengshun.modules.api.coal.repository.MerchantCoalRepository;
import com.pengshun.modules.api.coal.service.MerchantCoalService;
import com.pengshun.modules.api.coal.service.dto.MerchantCoalDto;
import com.pengshun.modules.api.coal.service.mapstruct.MerchantCoalTodo;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author lifei
 * @date 2020-11-12
 **/
@Service
@RequiredArgsConstructor
public class MerchantCoalServiceImpl implements MerchantCoalService {

    private final MerchantCoalRepository merchantCoalRepository;
    private final MerchantCoalTodo merchantCoalToDo;
    private final UserRepository userRepository;
    private final MerchantRepository merchantRepository;
    private final MessageSource messageSource;
    private final PsCoalMapper cm;
    private final MerchantCoalMapper merchantCoalMapper;

    @Override
    public BaseResult selectListBytId(Long merchantId) {
        List<MerchantCoal> coals = merchantCoalMapper.findByMerchantId(merchantId);
        List<MerchantCoalDto> coalDto = merchantCoalToDo.toDto(coals);
        return new BaseResult(0, coalDto);
    }


    @Override
    public BaseResult selectCoalDetil(Long merchantCoalId) {
        MerchantCoalDto dto = cm.selectMerchantCoalDetil(merchantCoalId);
        dto=todo(dto);
        MerchantCoal coal=merchantCoalRepository.findById(merchantCoalId).orElseGet(MerchantCoal::new);
        //浏览数加一
        int num =coal.getLookNumber()==null?0:coal.getLookNumber()+1;
        coal.setLookNumber(num);
        merchantCoalRepository.save(coal);
        return new BaseResult(0, dto);
    }
    private MerchantCoalDto todo(MerchantCoalDto dto){
        if (dto != null) {
            List<MerchantCoalInfoDto> merchantCoalInfos=new ArrayList<>();
            merchantCoalInfos.add(new MerchantCoalInfoDto("全水", dto.getWholeWater(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("內水", dto.getNsValue(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("干基灰分", dto.getSerchHuifen(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("空干基挥发", dto.getKfValue(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("收到基挥发", dto.getSfValue(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("干燥无灰基挥发", dto.getGfValue(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("含硫量", dto.getAllSulphur(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("焦渣特征", dto.getJzValue(), ""));
            merchantCoalInfos.add(new MerchantCoalInfoDto("固定碳", dto.getGtValue(), "%"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("空干基高位", dto.getKwValue(), "kCal/kg"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("收到基低位", dto.getSwValue(), "kCal/kg"));
            merchantCoalInfos.add(new MerchantCoalInfoDto("--", null, null));
            dto.setMerchantCoalInfos(merchantCoalInfos);
        }
        return  dto;

    }
    @Override
    public BaseResult selectListBy(CoalBinessPara para) throws Exception {
        int page = (para.getPage()) * para.getSize();
        para.setCoalCalorific("0".equals(para.getCoalCalorific()) ? null : para.getCoalCalorific());
        para.setCoalTechnologyCode("0".equals(para.getCoalTechnologyCode()) ? null : para.getCoalTechnologyCode());
        para.setAllSulphur("0".equals(para.getAllSulphur()) ? null : para.getAllSulphur());
        para.setSerchHuifen("0".equals(para.getSerchHuifen()) ? null : para.getSerchHuifen());
        String index=null;
        if(para.getSize()==4){
            index="2";
        }
        List<MerchantCoalResult> list = cm.selectListBy(para.getCategoryCode(), para.getStatus(), para.getProvinceId(),
                para.getCityId(), para.getDistrictId(), page < 0 ? 0 : page, para.getSize(), para.getLngX(), para.getLatY(), para.getLevel(),
                para.getSort(), para.getMineMouthId(), para.getCoalCalorific(), para.getAllSulphur(), para.getSerchHuifen(),
                para.getCoalTechnologyCode(), para.getName(),index,para.getCategoryName());

        return new BaseResult(0, list);
    }

//    @Override
//    public BaseResult selectListByStatus(Long userId, MerchantPara para) {
//        User user = userRepository.findById(userId).orElseGet(User::new);
//        para.setIsShow(1);
//        Specification<MerchantCoal> specification = new Specification<MerchantCoal>() {
//            @Override
//            public Predicate toPredicate(Root<MerchantCoal> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
//                List<Predicate> list = new ArrayList<>();
//                list.add(criteriaBuilder.equal(root.get("status"), para.getStatus()));
//                list.add(criteriaBuilder.equal(root.get("merchantId"), user.getMerchantId()));
//                list.add(criteriaBuilder.equal(root.get("isShow"), para.getIsShow()));
//                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
//            }
//        };

//        //status ==0  查询历史发布 数量 最后更新时间
//        Page<MerchantCoal> coalDto = merchantCoalRepository.findAll(specification, PageRequest.of(para.getPage(), para.getSize(), Sort.by(Sort.Direction.DESC, "issueTime")));
//        List<MerchantCoalDto> coalDtoList = merchantCoalMapper.toDto(coalDto.getContent());
//        Date date = coalDtoList.size() > 0 ? coalDtoList.get(0).getCreatTime() : null;
//        return new BaseResult(0, coalDto.getTotalElements(), coalDtoList.size() < para.getSize() ? false : true, coalDtoList, date);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult save(MerchantCoalDto form) throws Exception {
        User user = userRepository.findById(form.getUserId()).orElseGet(User::new);
        if (!user.getStatus().equals(AuthenticationStatus.TWO_STATUS)) {
            throw new Exception("该商户未认证贸易公司不能发布煤炭商品");
        }
        Merchant merchant = merchantRepository.findByUserId(form.getUserId());
        form.setMerchantId(merchant.getId());
        form.setMerchantName(merchant.getName());
        form.setStatus(CoalStatus.ONE_STATUS);
        form.setIssueStatus(CoalStatus.ZERO_STATUS);
        form.setReleaseNumber(form.getCoalNumber());
        form.setIsShow(1);
        form.setCreatBy(user.getName());
        form.setCreateTime(new Date());
        form.setCoalCalorific(form.getSwValue());
        merchantCoalRepository.save(merchantCoalToDo.toEntity(form));
        return new BaseResult(0, messageSource.getMessage("save.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult selectCoalList(PagePara para) {
        List<MerchantCoalDto> list=merchantCoalMapper.selectCoalList(para.getUserId(),para.getPage(),para.getSize(),para.getStatus());
            for (MerchantCoalDto merchantCoalDto : list) {
                if(!merchantCoalDto.getIssueStatus().equals(2)){
                    merchantCoalDto.setIssueTime(merchantCoalDto.getCreateTime());
                }
                if(para.getStatus().equals(3)){
                    merchantCoalDto.setIssueStatus(4);
                }
                if(para.getStatus().equals(0)&& System.currentTimeMillis()>merchantCoalDto.getOverTime().getTime()){
                    merchantCoalDto.setIssueStatus(4);
                }
            }
        return new BaseResult(0,list);
    }

    @Override
    public BaseResult selectMerchantCoalDetil(MerchantCoalPara para) {
        MerchantCoal coal=merchantCoalRepository.findById(para.getMerchantCoalId()).orElseGet(MerchantCoal::new);
        MerchantCoalDto dto=todo(merchantCoalToDo.toDto(coal));
        return new BaseResult(0,dto);
    }

    @Override
    public BaseResult update(MerchantCoalDto para) {
        MerchantCoal coal=merchantCoalRepository.findById(para.getMerchantCoalId()).orElseGet(MerchantCoal::new);
        //已发布不能修改
        if(coal.getIssueStatus().equals(CoalStatus.TWO_STATUS)){
            return new BaseResult(0, messageSource.getMessage("MerchantCoalServiceImpl.update.err", null, Locale.CHINA));
        }
        BeanUtils.copyProperties(para, coal, UpdateUtil.getNullPropertyNames(para));
        merchantCoalRepository.save(coal);
        return new BaseResult(0, messageSource.getMessage("update.success", null, Locale.CHINA));
    }


    @Override
    public BaseResult delete(Long merchantCoalId) {
        MerchantCoal coal=merchantCoalRepository.findById(merchantCoalId).orElseGet(MerchantCoal::new);
        //已发布煤炭商品无法删除
        if(coal.getIssueStatus().equals(CoalStatus.TWO_STATUS)){
            return new BaseResult(0, messageSource.getMessage("MerchantCoalServiceImpl.delete.err", null, Locale.CHINA));
        }
        coal.setStatus(CoalStatus.TWO_STATUS);
        merchantCoalRepository.save(coal);
        return new BaseResult(0, messageSource.getMessage("delete.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult issue(Long merchantCoalId) {
        MerchantCoal coal=merchantCoalRepository.findById(merchantCoalId).orElseGet(MerchantCoal::new);
        //不是未发布状态不能发布
        if(!coal.getIssueStatus().equals(CoalStatus.ZERO_STATUS)){
            return new BaseResult(0, messageSource.getMessage("MerchantCoalServiceImpl.issue.err", null, Locale.CHINA));
        }
        coal.setIssueStatus(CoalStatus.ONE_STATUS);
        merchantCoalRepository.save(coal);
        return new BaseResult(0, messageSource.getMessage("operation.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult show(MerchantCoalPara para) {
        MerchantCoal coal=merchantCoalRepository.findById(para.getMerchantCoalId()).orElseGet(MerchantCoal::new);
        coal.setIsShow(para.getIsShow());
        merchantCoalRepository.save(coal);
        return new BaseResult(0, messageSource.getMessage("operation.success", null, Locale.CHINA));
    }

}